﻿using System;
using System.IO;
using System.ComponentModel;
using System.Text;
using System.Web.Mvc;

namespace Flagwind.Web.Plugins.Controllers
{
	public class PluginExplorerController : Flagwind.Web.ControllerBase
	{
		#region 成员字段

		private Flagwind.Plugins.PluginContext _pluginContext;

		#endregion

		#region 构造方法

		public PluginExplorerController(Flagwind.Plugins.PluginContext pluginContext)
		{
			_pluginContext = pluginContext;
		}

		#endregion

		#region 行为方法

		public ActionResult Index(string path)
		{
			this.ViewData["PluginContext"] = _pluginContext;
			this.ViewData["PluginTree"] = _pluginContext.PluginTree;
			this.ViewData["Path"] = path == null ? string.Empty : path.Trim();

			var node = _pluginContext.PluginTree.RootNode;

			if(!string.IsNullOrWhiteSpace(path))
			{
				node = _pluginContext.PluginTree.Find(path) ?? _pluginContext.PluginTree.RootNode;
			}

			if(node == null)
			{
				this.ViewData["Target"] = null;
				this.ViewData["Target-Properties"] = null;
			}
			else
			{
				this.ViewData["Target"] = node.UnwrapValue(Flagwind.Plugins.ObtainMode.Never, null);
				this.ViewData["Target-Properties"] = TypeDescriptor.GetProperties(this.ViewData["Target"]);
			}

			return this.View(node);
		}

		public JsonResult Find(string path)
		{
			if(string.IsNullOrWhiteSpace(path))
			{
				return null;
			}

			var result = _pluginContext.ResolvePath(path);
			return new JsonResult(result);
		}

		#endregion

		#region 嵌套子类

		public class JsonResult : ActionResult
		{
			#region 成员字段

			private object _data;

			#endregion

			#region 构造函数

			public JsonResult(object data)
			{
				if(data == null)
				{
					throw new ArgumentNullException("data");
				}

				_data = data;
			}

			#endregion

			#region 重写方法

			public override void ExecuteResult(ControllerContext context)
			{
				var response = context.HttpContext.Response;

				response.ContentType = "application/json";
				response.ContentEncoding = Encoding.UTF8;

				using(var stream = new MemoryStream())
				{
					Flagwind.Runtime.Serialization.Serializer.Json.Serialize(stream, _data);
					stream.Position = 0;

					using(var reader = new StreamReader(stream))
					{
						response.Write(reader.ReadToEnd());
					}
				}
			}

			#endregion
		}

		#endregion
	}
}